package com.ruoyi.gp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gp.domain.Patient;
import com.ruoyi.gp.domain.bo.DoctorBo;
import com.ruoyi.gp.domain.vo.DoctorVo;
import com.ruoyi.gp.service.IDoctorService;
import com.ruoyi.gp.service.IPatientService;
import com.ruoyi.gp.domain.Doctor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.gp.domain.bo.CommunityBo;
import com.ruoyi.gp.domain.vo.CommunityVo;
import com.ruoyi.gp.domain.Community;
import com.ruoyi.gp.mapper.CommunityMapper;
import com.ruoyi.gp.service.ICommunityService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-04
 */
@RequiredArgsConstructor
@Service
public class CommunityServiceImpl implements ICommunityService {

    private final CommunityMapper baseMapper;

    private final IPatientService patientService;

    private final IDoctorService doctorService;
    /**
     * 查询【请填写功能名称】
     */
    @Override
    public CommunityVo queryById(Long communtiyId){
        return baseMapper.selectVoById(communtiyId);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public TableDataInfo<CommunityVo> queryPageList(CommunityBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Community> lqw = buildQueryWrapper(bo);
        Page<CommunityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @Override
    public List<CommunityVo> queryList(CommunityBo bo) {
        LambdaQueryWrapper<Community> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Community> buildQueryWrapper(CommunityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Community> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCommunityName()), Community::getCommunityName, bo.getCommunityName());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Community::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getEmail()), Community::getEmail, bo.getEmail());
        lqw.eq(bo.getSysUserId() != null, Community::getSysUserId, bo.getSysUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getLeader()), Community::getLeader, bo.getLeader());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), Community::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), Community::getAddress, bo.getAddress());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     */
    @Override
    public Boolean insertByBo(CommunityBo bo) {
        Community add = BeanUtil.toBean(bo, Community.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setCommunityId(add.getCommunityId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     */
    @Override
    public Boolean updateByBo(CommunityBo bo) {
        Community update = BeanUtil.toBean(bo, Community.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Community entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除【请填写功能名称】
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<CommunityVo> queryByCommunitys(PageQuery pageQuery) {
        Page<CommunityVo>result=baseMapper.selectVoPage(pageQuery.build(),null);
        for (CommunityVo communityVo : result.getRecords()) {
            long communityFinishCount=0;
            long communityNotFinish=0;
            long communityFamilyEnvironmentCount=0;
            long communityMedicationRecordsCount=0;
            DoctorBo doctorBo = new DoctorBo();
            doctorBo.setCommunityId(communityVo.getCommunityId());
            List<DoctorVo> doctorVos = doctorService.queryList(doctorBo);
            communityVo.setDoctors(doctorVos);
            //如果没有医生，则不进行循环
            if(ObjectUtil.isNotEmpty(doctorVos))
            for (DoctorVo doctorVo: communityVo.getDoctors()) {
                PageQuery page = new PageQuery();
                TableDataInfo<Patient> patients = patientService.queryByCount(doctorVo.getId(),page);
                long finishCount=0;
                long notFinish =0;
                long familyEnvironmentCount = 0;
                long medicationRecordsCount = 0;
                doctorVo.setPatients(patients.getRows());
                for (Patient patient : patients.getRows()) {
                    finishCount += patient.getFinishCount();
                    notFinish += patient.getNotFinish();
                    familyEnvironmentCount += patient.getFamilyEnvironmentCount();
                    medicationRecordsCount += patient.getMedicationRecordsCount();
                }
                doctorVo.setFinishCount(finishCount);
                doctorVo.setNotFinish(notFinish);
                doctorVo.setFamilyEnvironmentCount(familyEnvironmentCount);
                doctorVo.setMedicationRecordsCount(medicationRecordsCount);
                communityFinishCount+=doctorVo.getFinishCount();
                communityNotFinish += doctorVo.getNotFinish();
                communityFamilyEnvironmentCount += doctorVo.getFamilyEnvironmentCount();
                communityMedicationRecordsCount += doctorVo.getMedicationRecordsCount();
            }
            communityVo.setFinishCount(communityFinishCount);
            communityVo.setNotFinish(communityNotFinish);
            communityVo.setFamilyEnvironmentCount(communityFamilyEnvironmentCount);
            communityVo.setMedicationRecordsCount(communityMedicationRecordsCount);
        }
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<CommunityVo> queryByCommunitysByDoctors(PageQuery pageQuery) {
        List<CommunityVo> communityVoPage = baseMapper.queryByCommunitys();
        return TableDataInfo.build(communityVoPage);
    }
}
